package main

import (
	"context"
	"platon-tools/go-service/event"

	"github.com/urfave/cli/v2"
	"go.uber.org/zap"
	"os"
	"os/signal"
	go_logger "platon-tools/go-service/go-logger"
	"platon-tools/go-service/monitor/monitor_platon"
	"platon-tools/go-service/monitor/rpc"
	"syscall"
)

func appRun(ctx *cli.Context) error {
	sctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	feed := new(event.Event)

	ms := rpc.NewMonitorService(sctx, RpcConfig, feed)
	if err := ms.Start(); err != nil {
		go_logger.Logger.Error("setup monitor server failed", zap.Error(err))
		return err
	}

	node := monitor_platon.NewNode(sctx, &SpecialNodeConfig, feed)

	if err := node.Start(); err != nil {
		go_logger.Logger.Error("node setup failed", zap.Error(err))
		return err
	}

	appWait(cancel)

	return node.Close()
}

func appWait(cancelFunc context.CancelFunc) {
	sigs := make(chan os.Signal, 1)
	done := make(chan bool, 1)

	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		sig := <-sigs
		go_logger.Logger.Info(sig.String())
		done <- true
	}()

	go_logger.Logger.Info("waiting signal ...")
	<-done
	go_logger.Logger.Info("app quit ...")
	cancelFunc()
}
